/**
 * Heterotopia - an up-to-date Java-based MUD system
 * Copyright (C) 2011 Bill Garrett <memesis@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package heterotopia.ss;

import java.util.UUID;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

/**
 * The MinaSessionTrackingFilter notifies MinaHelper
 * of changes to the sessions to which it is attached.
 * 
 * @see heterotopia.ss.MinaHelper
 * 
 * @author garrett
 */
public class MinaSessionTrackerFilter extends IoFilterAdapter {
	private MinaHelper tracker;
	
	public MinaSessionTrackerFilter(MinaHelper tracker) {
		this.tracker = tracker;
	}

	/* (non-Javadoc)
	 * @see org.apache.mina.common.IoFilterAdapter#sessionClosed(org.apache.mina.common.IoFilter.NextFilter, org.apache.mina.common.IoSession)
	 */
	@Override
	public void sessionClosed(NextFilter nextFilter, IoSession session)
			throws Exception {
		if(session.containsAttribute(MinaHelper.SESSION_ID_KEY)) {
			UUID sessionId = (UUID) session.getAttribute(MinaHelper.SESSION_ID_KEY);
			tracker.sessionClosed(sessionId);
		}
		super.sessionClosed(nextFilter, session);
	}


	/* (non-Javadoc)
	 * @see org.apache.mina.common.IoFilterAdapter#sessionOpened(org.apache.mina.common.IoFilter.NextFilter, org.apache.mina.common.IoSession)
	 */
	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session)
			throws Exception {
		UUID sessionId = tracker.sessionOpened(session);
		session.setAttribute(MinaHelper.SESSION_ID_KEY, sessionId);
		super.sessionOpened(nextFilter, session);
	}
}